package cn.itcast.dmp.bean

import ch.hsr.geohash.GeoHash
import cn.itcast.dmp.config.AppConfigHelper
import com.maxmind.geoip.LookupService
import org.lionsoul.ip2region.{DbConfig, DbSearcher}
import com.maxmind.geoip.{Location, LookupService}
object IPUtils {
  def convertIp2Region(ip: String, dbSearcher: DbSearcher, lookupService: LookupService): IpRegion = {

    // TODO：a. 将IP地址转换为省份和城市
    val region: String = dbSearcher.btreeSearch(ip).getRegion
    val Array(_, _, province, city, _) = region.trim.split("\\|")

    // TODO: b. 将IP地址转换为经纬度
    val location: Location = lookupService.getLocation(ip)
    val longitude: Float = location.longitude
    val latitude: Float = location.latitude

    // TODO: c. 转换经纬度为GeoHash值
    val geoHash: String = GeoHash.geoHashStringWithCharacterPrecision(
      latitude, longitude, 8
    )

    // TODO: d. 封装解析的信息并返回
    IpRegion(ip, longitude.toDouble, latitude.toDouble, province, city, geoHash)
  }


  /**
    * 转换IP地址为经纬度、省份城市及GeoHash值
    *
    * @param ip IP地址
    * @return
    */
  def convertIp2Region(ip: String): IpRegion = {

    // TODO：a. 将IP地址转换为省份和城市
    val dbSearcher = new DbSearcher(new DbConfig(), AppConfigHelper.IPS_DATA_REGION_PATH)
    val region: String = dbSearcher.btreeSearch(ip).getRegion
    val Array(_, _, province, city, _) = region.trim.split("\\|")

    // TODO: b. 将IP地址转换为经纬度
    val lookupService = new LookupService(AppConfigHelper.IPS_DATA_GEO_PATH, LookupService.GEOIP_MEMORY_CACHE)
    val location: Location = lookupService.getLocation(ip)
    val longitude: Float = location.longitude
    val latitude: Float = location.latitude

    // TODO: c. 转换经纬度为GeoHash值
    val geoHash: String = GeoHash.geoHashStringWithCharacterPrecision(
      latitude, longitude, 8
    )

    // TODO: d. 封装解析的信息并返回
    IpRegion(ip, longitude.toDouble, latitude.toDouble, province, city, geoHash)
  }

  def main(args: Array[String]): Unit = {
    println(convertIp2Region("106.87.131.39"))
  }

}


